//
//  WBComposeTypeView.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/20.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit
import pop

/// 撰写微博视图
class WBComposeTypeView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var backBtnCenterXConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var closeBtnCenterXConstraint: NSLayoutConstraint!
    //完成回调
    private var completionBlock: ((_ clsName: String?) -> ())?
    
    private let buttonInfo = [["imageName": "","title": "文学","clsName": "WBComPoseViewController"],
                              ["imageName": "","title": "照片/视频"],
                              ["imageName": "","title": "长微博"],
                              ["imageName": "","title": "签到"],
                              ["imageName": "","title": "点评"],
                              ["imageName": "","title": "更多","actionName": "clickMore"],
                              ["imageName": "","title": "好友圈"],
                              ["imageName": "","title": "微博相机"],
                              ["imageName": "","title": "音乐"],
                              ["imageName": "","title": "拍摄"]]
    
    
    
    //MARK: 实例化方法
    class func composeTypeView() -> WBComposeTypeView {
        //从XIB加载完成视图，就会调用awakeFromNib
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        v.frame = UIScreen.main.bounds
        v.setUpUI()
        return v
    }
    
    /// 显示当前视图
    //OC中的block，如果当前方法不执行，通常使用属性记录，在需要的时候执行
    func show(compeletion: @escaping (_ clsName: String?) -> ()) {
        //记录闭包
        completionBlock = compeletion
        //将当前视图添加到跟视图控制器的view上
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        //添加视图
        vc.view.addSubview(self)
        //开始动画
        showCurrentView()
    }
    //监听方法
    @objc private func clickBtn(selectedButton: WBComposeTypeButton) {
        /// 遍历当前视图，选中的按钮放大，未选中的按钮变小
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        for (i, btn) in v.subviews.enumerated() {
            //缩放动画
            let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            //x,y在系统中用CGPoint表示，如果要转换成‘id’，需要用使用NSValue包装
            let scale = (selectedButton == btn) ? 2 : 0.2
            scaleAnim?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim?.duration = 0.5
            btn.pop_add(scaleAnim, forKey: nil)
            //渐变动画
            let alphaAnim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim?.toValue = 0.2
            alphaAnim?.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            //动画完成的回调监听
            if i == 0 {
                alphaAnim?.completionBlock = { (_, _)  -> (Void) in
                    print("动画结束啦")
                    //执行完成闭包
                    self.completionBlock?(selectedButton.clsName)
                }
            }
        }
        
    }
    @objc private func clickMore() {
        print("点了更多")
        //将scrollView滑动到第二页
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        //处理底部按钮，让两个按钮分开
        backButton.isHidden = false
        let margin = scrollView.bounds.width / 6
        closeBtnCenterXConstraint.constant += margin
        backBtnCenterXConstraint.constant -= margin
        UIView.animate(withDuration: 0.25) {
            self.layoutIfNeeded()
        }
    }
    
    @IBAction func back(_ sender: Any) {
        
        scrollView.setContentOffset(CGPoint(x: 0, y: 9), animated: true)
        closeBtnCenterXConstraint.constant = 0
        backBtnCenterXConstraint.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }) { (_) in
            self.backButton.isHidden = true
            self.backButton.alpha = 1
        }
    }
    
    
    @IBAction func close(_ sender: Any) {
//        removeFromSuperview()
        hideButtons()
    }
}
// MARK: - 动画添加扩展
private extension WBComposeTypeView {
    //消除动画部分
    func hideButtons() {
        //根据contentOffset判断scrollView当前显示的字视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        //遍历V中所有按钮
        for (i, btn) in v.subviews.enumerated().reversed() {
            //创建动画
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            anim?.fromValue = btn.center.y
            anim?.toValue = btn.center.y + 350
            //设置动画时间
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            //添加动画
            btn.layer.pop_add(anim, forKey: nil)
            //  监听第0个按钮，是最后一个执行的
            if i == 0 {
                anim?.completionBlock = { (_, _) -> (Void) in
                    self.hideCurrentView()
                }
            }
        }
    }
    //隐藏当前视图
    func hideCurrentView() {
        //创建动画
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        //设置动画属性
        anim?.fromValue = 1
        anim?.toValue = 0
        anim?.duration = 0.25
        pop_add(anim, forKey: nil)
        //添加监听完成的方法
        anim?.completionBlock = { (_, _) -> (Void) in
            self.removeFromSuperview()
        }
    }
    //显示动画部分
    func showCurrentView() {
        //创建动画
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 0
        anim?.toValue = 1
        anim?.duration = 0.25
        //添加到视图
        pop_add(anim, forKey: nil)
        //添加按钮的动画
        showButton()
    }
    /// 弹力显示所以按钮
    func showButton() {
        //获取scrollView视图的第0个视图
        let v = scrollView.subviews[0]
        //遍历v中所有的按钮
        for (i, btn) in v.subviews.enumerated() {
            /// 创建动画
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            anim?.fromValue = btn.center.y + 350
            anim?.toValue = btn.center.y
            //弹力系数，0-20，数值越大，弹力越大，默认是4
            anim?.springBounciness = 8
            //弹力速度，0-20，数值越大，速度越快，默认是12
            anim?.springSpeed = 12
            //设置动画启动时间
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            //添加动画
            btn.layer.pop_add(anim, forKey: nil)
        }
    }
}

// MARK: - private让 extension中的所有方法都是私有
private extension WBComposeTypeView {
    /// 创建类型按钮
    func setUpUI() {
        
        //0.强行更新布局
        layoutIfNeeded()
        let rect = scrollView.bounds
        let width = scrollView.bounds.width
        
        for i in 0..<2 {
            //1.向scrollView添加视图
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
            
            //2.向视图添加按钮
            addButtons(v: v, idx: i * 6)
            //将视图添加到scrollView
            scrollView.addSubview(v)
        }
        //设置scrollView
        scrollView.contentSize = CGSize(width: width * 2, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        //禁用滚动
        scrollView.isScrollEnabled = false
    }
    func addButtons(v: UIView, idx: Int) {
        let count = 6
        //从idx开始添加6个按钮
        for i in idx..<(idx + count) {
            if i >= buttonInfo.count {
                break
            }
            //从数组字典中获取图片和名称
            let dict = buttonInfo[i]
            guard let imageName = dict["imageName"], let title = dict["title"] else {
                continue
            }
              /// 1.创建按钮
              let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            ///2.将按钮添加到视图
            v.addSubview(btn)
            //添加监听事件
            if let actionName = dict["actionName"] {
                //OC 中使用NSSelectorFromString(@"clickMore")
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else {
                btn.addTarget(self, action: #selector(clickBtn), for: .touchUpInside)
            }
            //设置要展现的类名--不需要guard守护，有类名就设置，没有就不设置
            btn.clsName = dict["clsName"]
        }
        //遍历视图的字视图，布局按钮
        //准备常量
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4
        for (i, btn) in v.subviews.enumerated() {
            let y: CGFloat = (i > 2) ? (v.bounds.height - btnSize.height) : 0
            let col = i % 3
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
            
        }
    }
}
